/**
 * 
 */
package com.vssr.persist.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author srinivasarao_vassadi
 */
public class DBResourceUtil {

	public static void runScript(BufferedReader reader, Connection con) {
		String line, sqlQuery = "";
		try {
			if (con == null) {
				throw new Exception("Connection object can not be null");
			}
			Statement stmt = con.createStatement();
			// BufferedReader reader = new BufferedReader(new FileReader(
			// scriptFileName));

			while ((line = reader.readLine()) != null) {
				// Skip comments and empty lines
				// JOptionPane.showMessageDialog(null, line);
				if (line.length() > 0 && line.charAt(0) == '-'
						|| line.length() == 0) {
					continue;
				}
				sqlQuery = sqlQuery + " " + line;
				// If one command complete
				if (sqlQuery.charAt(sqlQuery.length() - 1) == ';') {
					sqlQuery = sqlQuery.replace(';', ' ');
					try {
						stmt.execute(sqlQuery);
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				sqlQuery = "";
			}
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
			System.exit(1);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void closeDBResources(Object obj) {

		if (obj == null) {
			return;
		}

		if (obj instanceof Statement) {
			Statement stmt = (Statement) obj;
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else if (obj instanceof ResultSet) {
			ResultSet rs = (ResultSet) obj;
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else if (obj instanceof Connection) {
			Connection con = (Connection) obj;
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
